package com.heima.gatway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.gatway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description: 认证过滤器
 * @Version: V1.0
 */
@Component
@Slf4j
@Order(-1) // 值越小越优先执行
public class AuthorizeFilter implements GlobalFilter {
    private static List<String> urlList = new ArrayList<>();
    // 初始化白名单 url路径
    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");
    }
    /**
     * 过滤方法
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1 判断当前是否是登录请求，如果是登录则放行
        String uri = request.getURI().getPath();
        for (String s : urlList) {
            if (uri.contains(s)){
                //包含就放行
                return chain.filter(exchange);
            }
        }
        //2 获取请求头jwt token信息
        String token = request.getHeaders().getFirst("token");
        //判断token是否为空
        if (StringUtils.isBlank(token)){
//            //返回401
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            //为空终止请求
//            return response.setComplete();
            //优化
            writeMessage(exchange,"token不能为空");
        }
        //3 解析令牌信息是否正确
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i < 1){
                //4如果解析成功，获取token中存放的用户id，并将id设置到请求头中路由给其他服务
                Object id = claimsBody.get("id");
                request.mutate().header("userId",id.toString());
                //认证成功放行请求
                return chain.filter(exchange);
            }else {
                log.error("解析token失败，原因:token已过期");
                return writeMessage(exchange,"解析token失败，原因:token已过期");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析token失败，原因{}",e.getMessage());
            return writeMessage(exchange,"解析token失败，原因:"+e.getMessage());
        }

//        //5 走到这失败返回结果
//        return response.setComplete();
    }
    /**
     * 返回错误提示信息
     * @return
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
